package com.example.myapplication.base;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.myapplication.util.ToastUtil;

import butterknife.ButterKnife;
import butterknife.Unbinder;


public abstract class BaseLazyFragment<P extends BasePresenter> extends Fragment implements BaseView {
    protected P mPresenter;


    private Unbinder bind;
    private View view;
    //Fragment是否可见
    private boolean mIsVisibleToUser;
    //视图是否创建
    private boolean mIsViewCreated;
    //是否有数据
    private boolean mDataLoaded;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(getLayout(), null);
            bind = ButterKnife.bind(this, view);
            mPresenter = initPresenter();
            if (mPresenter != null) {
                mPresenter.bindView(this);
            }
            initView(view);
            mIsViewCreated = true;
            lazyLoad();
            initListener();
        }else {
            bind = ButterKnife.bind(this, view);
        }

        return view;
    }

    private void lazyLoad() {
        if (mIsVisibleToUser && mIsViewCreated && !mDataLoaded) {
            mDataLoaded = true;
            //如果fragmnet每次显示都需要重新请求数据,在子类的initData中将mDataLoaded改成false
            initData();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.mIsVisibleToUser = isVisibleToUser;
        lazyLoad();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

       // bind.unbind();
        if (mPresenter != null) {
            mPresenter.destroy();
            mPresenter = null;
        }
        hideLoading();
    }

    protected abstract void initListener();

    protected abstract void initData();

    protected abstract void initView(View view);

    protected abstract P initPresenter();

    protected abstract int getLayout();



    @Override
    public void showToast(String msg) {
        ToastUtil.showToastLong(msg);
    }
}
